package yxy.game.pm2.command.pickedtroops;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PickedTroopsSlot;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PickedTroopsMessage;
import yxy.game.pm2.module.pickedtroops.PickedTroopsHandle;

import java.util.Map;

/****************************************
 * @name CMD_PickedTroopsSlots
 * @description 获取所有的或某阵容的兵符
 * @author 梁健彬
 * @since 2022-05-19
 ***************************************/
@MessageType(proto = Command.PickedTroopsSlots, classtype = PickedTroopsMessage.PickedTroopsSlotsRequest.class)
public class CMD_PickedTroopsSlots extends Command<PickedTroopsMessage.PickedTroopsSlotsRequest> {

    @Override
    public void execute(MessageSource messageSource, PickedTroopsMessage.PickedTroopsSlotsRequest request) {
        String playerCode = messageSource.getTag();
        int camp = request.getCamp();

        PickedTroopsMessage.PickedTroopsSlotsResponse.Builder response = PickedTroopsMessage.PickedTroopsSlotsResponse.newBuilder();

        try {
            Map<String, PickedTroopsSlot> slotMap = PickedTroopsSlot.all(playerCode);

            for (PickedTroopsSlot slot : slotMap.values()) {
                //如果正在使用则不返回
                if (!slot.getUse()) {
                    PickedTroopsMessage.PickedTroopsSlot pickedTroopsSlot = PickedTroopsHandle.packPickedTroopsSolt(slot, camp);
                    if (pickedTroopsSlot != null) response.addSlots(pickedTroopsSlot);
                }
            }
            send(messageSource, response, Result.Success);
        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        }
    }

    private void send(MessageSource messageSource, PickedTroopsMessage.PickedTroopsSlotsResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}